package com.hs.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hs.common.api.dto.ResultCode;
import com.hs.common.api.dto.ResultVo;
import com.hs.jwt.JwtTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author Bai Dingkun
 * @date 2022-07-14
 * @desc
 */
@Component
public class AuthorityFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtTemplate jwtTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//         1.匹配uri，判断是否需要权限校验
        String uriPath = request.getURI().getPath();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean matches = antPathMatcher.match("/**/auth/**",uriPath);
        if (matches){
//        2.获取请求头中的token
            String token = request.getHeaders().getFirst("Authorization");
//            3.判断token是否为空
            if (token == null){
                return errorHandle(response);
            }
//            4.校验token
//            解析获取用户id
            token = token.replace("Bearer ","");
            boolean verify = jwtTemplate.verify(token);
            if (!verify){
                return errorHandle(response);
            }
//            5.校验redis中的token
            String telephone = (String) jwtTemplate.parseToken(token, "telephone");
            String key = "user:token:" + telephone;
            String redisToken = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isEmpty(redisToken)){
                return errorHandle(response);
            }
//            redis中的token续约
            redisTemplate.expire(key, Duration.ofMinutes(30));
//            6.重写请求头
            ServerHttpRequest.Builder mutate = request.mutate();
            mutate.header("telephone",telephone);

        }
//          放行
        return chain.filter(exchange);
    }

    private Mono<Void> errorHandle(ServerHttpResponse response) {
        ResultVo resultVo = new ResultVo(ResultCode.PERMISSION_NO_ACCESS);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] resultBytes = new byte[0];
        try {
            resultBytes = objectMapper.writeValueAsBytes(resultVo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(resultBytes);
//                返回结果
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
